package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;

    //菜品列表分页查询
    @GetMapping("/dish/page")
    //@RequestParam(value = "page",defaultValue = "1")表示将传进来的page改名为pageNum 并且设置默认值1  即默认查询第一页(前端不传page的值时)
    public ResultInfo findByPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize, String name) {//默认每页10条

        Page<Dish> page = dishService.findByPage(pageNum, pageSize, name);
        return ResultInfo.success(page);
    }

    //新增菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        dishService.save(dish);
        return ResultInfo.success(null);
    }

    //修改  1.回显   2.update
    //回显菜品信息:通过id查到菜品信息 然后返回
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Dish dish = dishService.findById(id);
        return ResultInfo.success(dish);
    }

    //2.更新菜品信息
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {
        dishService.update(dish);
        return ResultInfo.success(null);
    }

    //启售/停售(单个/批量)
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        if (ids != null && ids.size() > 0) {
            dishService.updateStatus(status, ids);
        }
        return ResultInfo.success(null);
    }

    //删除(单个/批量)
    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            dishService.deleteByIds(ids);
        }
        return ResultInfo.success(null);
    }

    //通过套餐表的categoryId查询菜品   通过name模糊查询菜品
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryIdOrCategoryId(String name, Long categoryId) {
        if (categoryId != null) {
            Integer status = 1;//表示在售
            List<Dish> dishList = dishService.findDishOnSale(categoryId,status);
            return ResultInfo.success(dishList);
        }
        if (StringUtils.isNotEmpty(name)) {
            List<Dish> dishList = dishService.findByName(name);
            return ResultInfo.success(dishList);
        }
        return ResultInfo.error("参数传递错误!");
    }
}
